package com.leonzx.base.config.filter;

import com.leonzx.base.entity.system.User;
import com.leonzx.base.utils.RedisConstants;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;

/**
 * Created by 梁亮 on 2017/4/28.
 */
public class SystemLogoutFilter extends LogoutFilter {
    /**
     * 缓存
     */
    private Cache<String, Deque<Serializable>> cache;

    //设置Cache的key的前缀
    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache(RedisConstants.SHIRO_REDIS_CACHE);
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        //在这里执行退出系统前需要清空的数据
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        try {
            /*是否需要将session销毁*/
            User user = (User) subject.getPrincipal();
            String username = user.getUsername();
            //清除缓存
            cache.remove(username);
            subject.logout();
        } catch (SessionException ise) {
            ise.printStackTrace();
        }
        issueRedirect(request, response, redirectUrl);
        //返回false表示不执行后续的过滤器，直接返回跳转到登录页面
        return false;
    }
}
